#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <stdio.h>

#include "Vector3.h"

//extern "C" __global__ void dev_sumVector(float* r, const float* a, const float* b, int num);
extern "C" void sumVector(Vector3* r, Vector3* v1, Vector3* v2, int numElements);

__global__ void dev_sumVector(float* r, const float* a, const float* b, int num) {

	int tid = blockIdx.x * blockDim.x + threadIdx.x;

	if (tid < num) {
		r[tid] = a[tid] + b[tid];
	}
}

void sumVector(Vector3* r, Vector3* v1, Vector3* v2, int numElements) {

	float *dev_r, *dev_a, *dev_b;

	size_t size = 3 * numElements * sizeof(float);

	cudaMalloc( (void**)&dev_r, size );
	cudaMalloc( (void**)&dev_a, size );
	cudaMalloc( (void**)&dev_b, size );

	cudaMemcpy( dev_a, v1, size, cudaMemcpyHostToDevice );
	cudaMemcpy( dev_b, v2, size, cudaMemcpyHostToDevice );

	int threadsPerBlock = 256;
	int blocksPerGrid = (3 * numElements + threadsPerBlock - 1) / threadsPerBlock;

	dev_sumVector<<<blocksPerGrid, threadsPerBlock>>> (dev_r, dev_a, dev_b, 3 * numElements);

	cudaMemcpy( r, dev_r, size, cudaMemcpyDeviceToHost );

	cudaFree(dev_r);
	cudaFree(dev_a);
	cudaFree(dev_b);

}